import { default as BasePopover, type PopoverProps } from '@mui/material/Popover';
import { useControlledState } from '@/hooks';

export type IPopoverProps = Omit<PopoverProps, 'children' | 'content' | 'open'> & {
  children: React.ReactNode;
  label?: PopoverProps['content'];
  content?: PopoverProps['children'];
  open?: boolean;
  trigger?: 'click' | 'hover';
  onOpenChange?: (open?: boolean) => void;
};

export const Popover = (props: IPopoverProps) => {
  const { trigger, label, children, content, open: propOpen, onOpenChange, ...popoverProps } = props;
  const [open, setOpen] = useControlledState(propOpen, onOpenChange);

  const onClick = () => {
    if (trigger === 'click') setOpen(!open);
  };

  const onMouseEnter = () => {
    if (trigger === 'hover') setOpen(true);
  };

  const onMouseLeave = () => {
    if (trigger === 'hover') setOpen(false);
  };

  return (
    <>
      <div onClick={onClick} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
        {children}
      </div>
      <BasePopover open={!!open} onClose={() => setOpen(false)} content={label} {...popoverProps}>
        {content}
      </BasePopover>
    </>
  );
};
